var request_handler = global.request_handler
var usermgr = global.usermgr
var roommgr = global.roommgr
var sql = global.mysqldb

var handle_error = function (hbsocket, errorinfo, reqId) {
    hbsocket.response(reqId, '', { error: errorinfo });
}

request_handler['login_game'] = function (hbsocket, msg, reqId) {
    var account = msg.account;
    if(account == null){
        hbsocket.response(reqId, 'login_game', { error: 'account 为空' });
    }

    hbsocket.account = account;

    var user = usermgr.get(account);
    if (user) {
        user.kickOff('账号在另一处登入');
    }

    user = usermgr.bind(account, hbsocket);

    var dealUser = function(account, data){
        sql.getUserCards(account, function(result, data2){   
            user.allcards = data2;
            user.name = data.name;
            user.cardgroups = JSON.parse(data.cardgroups);
            user.setongroup = data.setongroup;
            user.initGameCards();
            hbsocket.response(reqId, 'login_game', user.toData());
        });
    };

    sql.isUserExist(account, function (result, data) {
        if (result) {
            dealUser(account, data);
        }
        else {
            var t = new Date().getTime();
            var name = 'test_' + t;
            sql.createUser(account, name, null, null, function (result, data) {
                dealUser(account, data);
            });
        }
    })
};

request_handler['join_room'] = function (hbsocket, msg, reqId) {
    var roomid = msg.roomId;
    var account = hbsocket.account;

    if (roomid == null) {
        handle_error(hbsocket, 'roomid is null!', reqId);
        return;
    }
    
    if (account == null) {
        handle_error(hbsocket, 'account is null!', reqId);
        return;
    }

    var data = {
        succeed: true, 
    }

    hbsocket.response(reqId, 'join_room', data);

    var room = roommgr.getOrCreateRoomById(roomid);
    room.joinWithAccount(account); 
};

request_handler['buy_card'] = function (hbsocket, msg, reqId) {
    var account = hbsocket.account;
    sql.addCardsToUser([1,2,1],account,function(){});

    var data = {
        succeed: true, 
    }
    hbsocket.response(reqId, 'buy_card', data);
};